package com.qt.zuulclient.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qt.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Despription:
 *
 * @Autor: xusl
 * @Date: 2019/6/20 10:26
 * @Version: 1.0
 **/
@Component
public class ZuulClientFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public String filterType() {
        // 前置过滤器
        return "pre";
    }

    @Override
    public int filterOrder() {
        // 优先级为0，数字越大，优先级越低
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 是否执行该过滤器，此处为true，说明需要过滤
        return true;
    }

    @Override
    public Object run() throws ZuulException {
//        RequestContext currentContext = RequestContext.getCurrentContext();
//        HttpServletRequest request = currentContext.getRequest();
//        //如果是网关转发请求 放行
//        if (request.getMethod().equals("OPTIONS")) {
//            return null;
//        }
//        //如果是登陆 放行
//        String url = request.getRequestURL().toString();
//        if (url.indexOf("/login") > 0) {
//            System.out.println("登陆页面" + url);
//            return null;
//        }
//        //获取头信息
//        String authorization = request.getHeader("Authorization");
//        if (authorization != null && authorization.startsWith("Bearer ")) {
//            String token = authorization.substring(7);
//            Claims claims = jwtUtil.parseJWT(token);
//            if (claims != null) {
//                if ("admin".equals(claims.get("roles"))) {
//                    currentContext.addZuulRequestHeader("Authorization", authorization);
//                    System.out.println("token 验证通过，添加了头信息 " + authorization);
//                    return null;
//                }
//            }
//        }
//        currentContext.setSendZuulResponse(false);//终止运行
//        currentContext.setResponseStatusCode(HttpServletResponse.SC_FORBIDDEN);//http状态码
//        currentContext.setResponseBody("无权访问");
//        currentContext.getResponse().setContentType("text/html;charset=UTF‐8");
        return null;
    }
}
